package com.loop.unclelend.utils.dialog

import android.annotation.SuppressLint
import android.content.Context
import android.graphics.Color
import android.text.Editable
import android.text.TextWatcher
import android.view.LayoutInflater
import android.view.View
import android.view.inputmethod.EditorInfo
import android.widget.LinearLayout
import androidx.recyclerview.widget.DefaultItemAnimator
import androidx.recyclerview.widget.GridLayoutManager
import androidx.recyclerview.widget.RecyclerView
import com.loop.unclelend.R
import com.loop.unclelend.databinding.UncleDialogBindCardBinding
import com.loop.unclelend.pro.ProDialog
import com.loop.unclelend.utils.DensityUtils
import com.loop.unclelend.utils.ImageUtil
import com.loop.unclelend.utils.adapter.UncleRecyclerViewAdapter
import com.loop.unclelend.utils.adapter.UncleViewHolderHelper
import com.loop.unclelend.utils.decoration.GridSpacingItemDecoration
import com.loop.unclelend.utils.event.UncleEventHelper
import com.loop.unclelend.utils.event.UncleEventType
import com.loop.unclelend.utils.helper.CustomConfigsHelper
import org.json.JSONObject

/**
 * UncleLend
 * @Author wwdeng
 * @CreateTime: 2024/9/20 13:45
 * @Annotation：绑卡dialog
 */
class Dialog_BindCard: ProDialog {
    private lateinit var binding: UncleDialogBindCardBinding
    private var mCallback: IDialogCallback? = null
    //事件备注
    private var eventRemark = ""

    var itemAdapter: ItemAdapter? = null

    constructor(context: Context?) : super(context) {}
    constructor(context: Context?, callback: IDialogCallback?) : super(context) {
        mCallback = callback
    }

    constructor(context: Context?, remark: String,callback: IDialogCallback?) : super(context) {
        mCallback = callback
        eventRemark = remark
    }

    /**
     * 设置点击回调
     */
    fun setOnClick(callback: IDialogCallback){
        this.mCallback = callback
    }

    override fun getRootView(): View {
        binding = UncleDialogBindCardBinding.inflate(LayoutInflater.from(context))
        return binding.root
    }

    override fun initView() {
        initRecyclerView()
        showTypeDefaultView()
        checkSubmitStatus()
    }

    override fun initListener() {
        setOnClickListener(binding.imgClose)
        setOnClickListener(binding.btnAjouter)

        binding.editNumber.addTextChangedListener(ITextWatcher)
        binding.editNumberComplete.addTextChangedListener(ITextWatcher)
        binding.editNumber.onFocusChangeListener = IFocusChangeListener
        binding.editNumberComplete.onFocusChangeListener = IFocusChangeListener
        binding.editNumber.setOnEditorActionListener { v, actionId, event ->
            if (actionId == EditorInfo.IME_ACTION_DONE){
                binding.editNumber.clearFocus()
                true
            }
            false
        }
        binding.editNumberComplete.setOnEditorActionListener { v, actionId, event ->
            if (actionId == EditorInfo.IME_ACTION_DONE){
                binding.editNumberComplete.clearFocus()
                true
            }
            false
        }
    }

    override fun initData() {
        val bindList = arrayListOf<JSONObject>()
        val customize = CustomConfigsHelper.getUncleConfigData()
        if (customize != null){
            val walletChannels = customize.optJSONArray("walletChannels")
            if (walletChannels != null && walletChannels.length() > 0){
                for (i in 0..<walletChannels.length()){
                    val item = walletChannels.optJSONObject(i)
                    item.put("isSelect", false)
                    bindList.add(item)
                }
            }
        }
        itemAdapter!!.data = bindList
    }

    override fun onViewClick(v: View?) {
        when(v!!.id){
            R.id.img_close -> {
                dismiss()
            }
            R.id.btn_ajouter -> {//提交
                val typeObj = getSelectTypeItem() ?: return
                if (getPhoneNumber() != getPhoneNumberComplete()){
                    showTypeErrorView()
                    return
                }
                UncleEventHelper.addUncleRequestEventAction(UncleEventType.CLICK.UNCLE_CLICK_USER_ACCOUNT_ADD_SUBMIT,eventRemark)
                if(mCallback != null){
                    mCallback!!.onSubmitParams(typeObj,getPhoneNumber())
                }
                dismiss()
            }
        }
    }

    /**
     * 初始化类型列表
     */
    @SuppressLint("NotifyDataSetChanged")
    private fun initRecyclerView() {
        val layoutManager = GridLayoutManager(context,2)
        binding.recyclerView.layoutManager = layoutManager
        itemAdapter = ItemAdapter(binding.recyclerView)
        val leftDecoration = DensityUtils.dp2px(10f)
        binding.recyclerView.addItemDecoration(GridSpacingItemDecoration(2, leftDecoration, false))
        binding.recyclerView.adapter = itemAdapter!!
        binding.recyclerView.itemAnimator = DefaultItemAnimator()
        itemAdapter!!.setOnItemChildClickListener { _, childView, position ->
            val model = itemAdapter!!.getItem(position)
            if (childView.id == R.id.layout_item) {//切换item
                for (i in 0..<itemAdapter!!.itemCount) {
                    val item = itemAdapter!!.getItem(i)
                    if (i == position) {
                        item.put("isSelect", true)
                    } else {
                        item.put("isSelect", false)
                    }
                }
                itemAdapter!!.notifyDataSetChanged()
                checkSubmitStatus()
                UncleEventHelper.addUncleRequestEventAction(UncleEventType.CLICK.UNCLE_CLICK_USER_ACCOUNT_ADD_TYPE_CHECK, model.optString("desc"))
            }
        }
    }

    /**
     * 输入框监听
     */
    private val ITextWatcher = object: TextWatcher{
        override fun beforeTextChanged(s: CharSequence?, start: Int, count: Int, after: Int) {
        }
        override fun onTextChanged(s: CharSequence?, start: Int, before: Int, count: Int) {
        }
        override fun afterTextChanged(s: Editable?) {
            showTypeDefaultView()
            checkSubmitStatus()
        }
    }

    /**
     * 焦点变化监听
     */
    private val IFocusChangeListener = View.OnFocusChangeListener { v, hasFocus ->
        if (!hasFocus){
            if (v.id == R.id.edit_number){
                val mobile = binding.editNumber.text.toString().trim()
                if (mobile.isNotEmpty()){
                    UncleEventHelper.addUncleRequestEventAction(UncleEventType.FORM.UNCLE_FORM_USER_ACCOUNT_ADD_MOBILE,mobile)
                }
            } else {
                val mobile = binding.editNumberComplete.text.toString().trim()
                if (mobile.isNotEmpty()){
                    UncleEventHelper.addUncleRequestEventAction(UncleEventType.FORM.UNCLE_FORM_USER_ACCOUNT_ADD_MOBILE,mobile)
                }
            }
        }
    }

    /**
     * 设置默认样式
     */
    private fun showTypeDefaultView(){
        binding.layoutTips.setBackgroundColor(Color.parseColor("#00000000"))
        binding.editNumber.setBackgroundResource(R.drawable.radius_fill_fff2f0f5_8)
        binding.editNumber.setTextColor(Color.parseColor("#FF100437"))
        binding.editNumberComplete.setBackgroundResource(R.drawable.radius_fill_fff2f0f5_8)
        binding.editNumberComplete.setTextColor(Color.parseColor("#FF100437"))
        binding.layoutErrorTips.visibility = View.GONE
    }

    /**
     * 设置号码错误提示
     */
    private fun showTypeErrorView(){
        binding.layoutTips.setBackgroundResource(R.drawable.radius_fill_fffff0ef_8)
        binding.editNumber.setBackgroundResource(R.drawable.radius_frame_fff86f00_8)
        binding.editNumber.setTextColor(Color.parseColor("#FFF86F00"))
        binding.editNumberComplete.setBackgroundResource(R.drawable.radius_frame_fff86f00_8)
        binding.editNumberComplete.setTextColor(Color.parseColor("#FFF86F00"))
        binding.layoutErrorTips.visibility = View.VISIBLE
    }

    /**
     * 切换Ajouter按钮是否可点击
     */
    fun checkSubmitStatus(){
        if (getSelectTypeItem() != null && getPhoneNumber().isNotEmpty() && getPhoneNumberComplete().isNotEmpty() && (getPhoneNumber() == getPhoneNumberComplete())){
            binding.btnAjouter.isEnabled = true
            binding.btnAjouter.alpha = 1f
        } else {
            binding.btnAjouter.isEnabled = false
            binding.btnAjouter.alpha = 0.4f
        }
    }

    /**
     * 获取选择的账户类型
     */
    private fun getSelectTypeItem(): JSONObject?{
        var obj: JSONObject? = null
        for (item in itemAdapter!!.data) {
            if (item.optBoolean("isSelect", false)){
                obj = item
                break
            }
        }
        return obj
    }

    /**
     * 获取输入的手机号码
     */
    private fun getPhoneNumber(): String{
        return binding.editNumber.text.toString()
    }

    /**
     * 获取确认手机号码
     */
    private fun getPhoneNumberComplete(): String{
        return binding.editNumberComplete.text.toString()
    }

    class ItemAdapter(recyclerView: RecyclerView?) : UncleRecyclerViewAdapter<JSONObject>(recyclerView, R.layout.uncle_item_bind_card_type) {
        override fun setItemChildListener(helper: UncleViewHolderHelper, viewType: Int) {
            helper.setItemChildClickListener(R.id.layout_item) //点击Item
        }
        override fun fillData(helper: UncleViewHolderHelper, position: Int, model: JSONObject) {
            val isSelect = model.optBoolean("isSelect", false)
            val itemLayout = helper.getView<LinearLayout>(R.id.layout_item)
            val imgLogo = helper.getImageView(R.id.img_logo)
            val textTitle = helper.getTextView(R.id.txt_title)
            textTitle.text = model.optString("desc")
            ImageUtil.instance!!.loadImageUrl(mContext,imgLogo,model.optString("logo"), R.mipmap.icon_holder)

            val imgSelect = helper.getImageView(R.id.img_select)
            if (isSelect) {
                itemLayout.setBackgroundResource(R.drawable.radius_fill_ff7000ff_10)
                textTitle.setTextColor(Color.parseColor("#FFFFFFFF"))
                imgSelect.setImageResource(R.mipmap.icon_bind_card_type_select)
            } else {
                itemLayout.setBackgroundResource(R.drawable.radius_fill_fff2f0f5_10)
                textTitle.setTextColor(Color.parseColor("#FF747378"))
                imgSelect.setImageResource(R.mipmap.icon_bind_card_type_normal)
            }
        }
    }

    interface IDialogCallback {
        //按钮点击
        fun onClick(view: View?)
        //确认
        fun onSubmitParams(typeObj: JSONObject,phoneNumber: String)
    }

    override fun onStart() {
        super.onStart()
        UncleEventHelper.addUncleRequestEventAction(UncleEventType.DIALOG.UNCLE_DIALOG_USER_ACCOUNT_ADD_SHOW,eventRemark)
    }

    override fun dismiss() {
        super.dismiss()
        UncleEventHelper.addUncleRequestEventAction(UncleEventType.DIALOG.UNCLE_DIALOG_USER_ACCOUNT_ADD_DISMISS,eventRemark)
    }
}